//
// Created by liushuai on 2021/2/21.
//

#include "licenseKeyFormatting.h"
// 超时
string licenseKeyFormatting(string S, int K){
    int index = S.size()-1;
    string res="";
    int seg = 0;
    while (index>=0){
        int count = 0;
        string temp= "";
        while (index>=0&&count<K){
            if(S[index]!='-'){
                count+=1;
                char val = (S[index]|32);
                if(val>='a'&&val<='z')
                    val=val-32;
                temp = val+temp;
            }
            index--;
        }
        if(count == K)
            seg+=1;
        if((seg == 1&& index>-1)||(seg == 1&& index==-1&&temp.size()==K)||seg==0)
            res = temp;
        else{
            if(temp.empty())
                res = temp+res;
            else
                res =temp+'-'+res;
        }
    }
    return res;

}